package StudyCode.summary.mycollection;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;

/**
 * 版权所有 科技与人文(www.tah1986.com)
 */
public class CountsTheNumberOfOccurrencesOfEachWordInAString {
	public static void main(String[] args) {
		Map<String, Integer> myMap = new HashMap<>();

		createMap(myMap);
		displayMap(myMap);
	}

	private static void createMap(Map<String, Integer> map) {
		String input = "this is a test this is a test";

		String[] tokens = input.split(" ");

		for (String token : tokens) {
			String word = token.toLowerCase();

			if (map.containsKey(word)) {
				int count = map.get(word);
				map.put(word, count + 1);
			} else
				map.put(word, 1);
		}
	}

	private static void displayMap(Map<String, Integer> map) {
		Set<String> keys = map.keySet();

		TreeSet<String> sortedKeys = new TreeSet<>(keys);

		System.out.printf("%nMap 包含:%nKey\t\tValue%n");

		for (String key : sortedKeys)
			System.out.printf("%-10s%10s%n", key, map.get(key));

		System.out.printf("%n大小: %d%n是空的: %b%n", map.size(), map.isEmpty());
	}
}
